package com.zbj.homemade.mybatis.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: principle
 * @description:
 * @author: Yinn
 * @create: 2019-01-11 16:22
 **/
public class SqlFill {

    //${xxx}
    private static final Pattern $p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");

    private static final Pattern octothorpe = Pattern.compile("(\\#\\{)([\\w]+)(\\})");

    //顺序替换 只替换#{xxx} 省事
    public static String replace(String sql, Object[] params) {

        Matcher octothorpe_m = octothorpe.matcher(sql);
        StringBuffer sb = new StringBuffer();

        SqlFill.replace(octothorpe_m, params, sb);

        return sb.toString();
    }

    private static StringBuffer replace(Matcher m, Object[] params, StringBuffer sb) {

        int count = 0;
        while (m.find()) {

            if (count + 1 > params.length){
                throw new RuntimeException("参数与入参数量不对应！");
            }

            Object param = params[count];
            if (param == null)
                param = "null";

            //下一步是替换并且把替换好的值放到sb中
            m.appendReplacement(sb, String.valueOf(param));
            count++;
        }
        //把符合的数据追加到sb尾
        m.appendTail(sb);

        return sb;
    }
}
